import React, { Component } from 'react'
import { List, Button, Popconfirm, message } from 'antd';
import Article from '../../../../../types/Article';
import { deleteArticle, queryAllArticles } from '../../../../../api/blog';
import { Link, RouteComponentProps, withRouter } from 'react-router-dom';
import ButtonGroup from 'antd/lib/button/button-group';

interface IProps extends RouteComponentProps { }
interface IState {
    articles: Article[];
    isLoading: boolean;
}
class EditArticleList extends Component<IProps, IState> {
    onDeleteBlog = async (articleID: number) => {
        this.setState({ isLoading: true });
        const res = await deleteArticle(articleID);
        if (res) {
            message.success('删除成功');
        } else {
            message.error("删除成功")
        }
        await this.getArticles();
        this.setState({ isLoading: false });
    }
    constructor(props: IProps) {
        super(props);
        this.state = {
            articles: [],
            isLoading: true
        }
    }

    async componentDidMount() {
        await this.getArticles();
        this.setState({
            isLoading: false
        })
    }

    getArticles = async () => {
        const articles = await queryAllArticles();
        this.setState({
            articles: articles
        })
    }

    render() {
        const { articles, isLoading } = this.state;
        return (
            <List
                className="demo-loadmore-list"
                loading={isLoading}
                itemLayout="horizontal"
                dataSource={articles}
                renderItem={item => (
                    <List.Item
                        key={item.articleID}
                        actions={[
                            <ButtonGroup>
                                <Button onClick={() => { this.props.history.push(`/mani/article/edit/${item.articleID}`) }} >编辑</Button>
                                <Popconfirm
                                    title="确认删除吗？"
                                    okText="确认"
                                    cancelText="取消"
                                    onConfirm={this.onDeleteBlog.bind(this, item.articleID)}
                                >
                                    <Button danger>删除</Button>
                                </Popconfirm>
                            </ButtonGroup>
                        ]}
                    >
                        <List.Item.Meta
                            title={<Link to='/'><h1>{item.title}</h1></Link>}
                            description={item.cate.cateName}
                        />
                    </List.Item>
                )}
            />
        )
    }
}
export default withRouter(EditArticleList);